/**
 * Created by hjqi on 2016/7/22.
 */
angular.module('NatureCloud').factory('svcCommonService',function (k8sService) {
  var _common ={
    //设置服务的起停状态
    setIconClass:function(service){
      if (service.totalStatue == 'running'){
        service.statusIconClass = "fa-play-circle text-secondary";
        service.btn_title = '停止服务';
        service.btn_icon= 'fa-pause';
      }
      else if (service.totalStatue == 'starting' ||
        service.totalStatue == 'stoping'  ||
        service.totalStatue == 'restarting' ||
        service.totalStatue == 'scaling' ||
        service.totalStatue == 'updating' ){
        service.statusIconClass = "fa-clock-o text-warning";
        if(service.totalStatue == 'restarting' || service.totalStatue == 'updating' || service.totalStatue == 'scaling'){
          service.btn_title = '停止服务';
          service.btn_icon= 'fa-pause';
        }else{
          service.btn_icon= 'fa fa-spinner fa-spin';
        }
      }
      else if (service.totalStatue == 'stop'){
        service.statusIconClass = "fa-pause text-muted";
        service.btn_title = '启动服务';
        service.btn_icon= 'fa-play';
      }

      else if (service.totalStatue == 'error'){
        service.statusIconClass = "fa fa-times text-danger";
        service.btn_title = '停止服务';
        service.btn_icon= 'fa fa-spinner fa-spin';
        // service.btn_icon= 'fa-stop';
      }
    },
    isServiceInMidStatus:function(service){
      return ( service.totalStatue === "starting"
      || service.totalStatue === "restarting"
      || service.totalStatue === "stoping"
      || service.totalStatue === "updating"
      || service.totalStatue === "scaling" );
    },
    /**
     Pod 的几种状态：
     "Pending":"starting",
     "Running":"running",
     "Succeeded":"stop",
     "Failed":"error",
     "Terminating":"stoping",
     "Unknown":"error"
     Container的几种状态（不准确，当pod为Terminating的时候，containerstatus就不会再更新了，所以当创建过程中停止时候会出现pod terminating，container 为creating）：
     "waiting":"",
     "running":"running",
     "terminated":"stop"
     */
    getpodstatus:function(svc,cb,podId){
      var podIds=podId?podId:"";
      k8sService.getpodStatus(svc.dbJson).then(function (ret) {
        var clusterId = svc.dbJson.node.clusterId,
          pods =  ret.data.items,
          app = svc.app  ,
          status = [];
        if(podIds==""){
          svcHanding(ret.data.items,app,status,clusterId)


        }else{
          svcHanding([podIds],app,status,clusterId)
        }

        //oops,ball ache ,there is no callback func here ,so...
        if(cb === undefined ){
          cb =  function(data){
            console.log("nop!dead channel...") ;
          }
        }
        // console.log("callback="+cb) ;
        try{
          if(ret.data.items.length === 0){
            cb([],svc);
          }else{
            if( svc ){
              cb(status,svc);
            }else{
              cb(status);
            }
          }
        }catch (e){
          console.log("Error:"+e) ;
        }

      },function(ret){
        console.log("service operate error,maybe the server stopped!") ;
        //may
        //alertify.alert("service operate error","get service status failed");
      });
    },
    getRcStatus:function(svc,cb){

      k8sService.getRcStatus(svc.dbJson).then(function (ret) {
        var rcList = ret.data ;
        if( cb ){
          cb( rcList,svc ) ;
        }
      },function(ret){
        console.log("service operate error,maybe the server stopped!") ;
        //may
        //alertify.alert("service operate error","get service status failed");
      });
    },
    getDefaultPodStatus:function(svc,cb){
      //从k8s中获取pod信息
      k8sService.getDefaultPodStatus(svc).then(function (ret) {

        var status = [];
        for (var j = 0; j < ret.data.items.length; j++) {
          var _st = {};
          var _item = ret.data.items[j];
          if (_item.status.containerStatuses) {
            _st.phase = getState(_item.status.containerStatuses[0].state);
            if(_st.phase === 'waiting'){
              if(_item.status.containerStatuses[0].state['waiting'].reason !== undefined &&
                _item.status.containerStatuses[0].state['waiting'].reason === 'CrashLoopBackOff')
                _st.phase = 'Error';
            }
            _st.lastState = _item.status.containerStatuses[0].lastState;
          }else
            _st.phase = _item.status.phase;


          _st.replicasname =  _item.metadata.name;
          _st.version = _item.metadata.labels.version;

          status.push(_st);
        }

        cb(status);

      },function(ret){
        console.log("service operate error,maybe the server stopped!"+JSON.stringify( ret )) ;
        //alertify.error("service operate error,get service status failed");
      });
    }
  };//end of obj common

  function getState(obj){
    for (var st in obj) {
      return st;
    }
  }

  function svcHanding (ret,app,status,clusterId) {
    for (var j = 0; j < ret.length; j++) {
      var _st = {};
      var _item = ret[j];
      var podPhase = _item.status.phase;

      if (_item.status.containerStatuses) {
        _st.phase = getState(_item.status.containerStatuses[0].state); //container's status
        if (_st.phase === 'waiting') {
          if (_item.status.containerStatuses[0].state['waiting'].reason !== undefined &&
            (_item.status.containerStatuses[0].state['waiting'].reason === 'CrashLoopBackOff'
            || _item.status.containerStatuses[0].state['waiting'].reason === 'ImagePullBackOff')) {
            _st.phase = 'Error';
            console.log("[Error][svcCommonServer.js] Container " + _item.status.containerStatuses[0].state['waiting'].reason);
          } else {
            if (podPhase === "Terminating") {
              _st.phase = 'stoping';
            } else if (podPhase === "Pending") {
              _st.phase = 'starting';
            }
          }
        }
        _st.lastState = _item.status.containerStatuses[0].lastState; //container's last status
      } else {
        _st.phase = podPhase;
        if ("Failed" == _st.phase) {
          console.log("[Error][svcCommonServer.js] One Pod failed");
        } else if ("Succeeded" == _st.phase) {
          _st.phase = "stop";
        } else {
          _st.phase = "error"; //pop  Unknown
        }
      }

      _st.replicasname = _item.metadata.name;    //Pod's name
      _st.version = _item.metadata.labels.version;//image's version
      _st.clusterId = clusterId;
      _st.app = app;
      status.push(_st);
    }
  }


  return _common;
});